package com.lib.framework.utils

import android.app.*
import android.content.*
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.graphics.BitmapFactory
import android.graphics.Point
import android.graphics.Rect
import android.media.RingtoneManager
import android.net.ConnectivityManager
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Binder
import android.os.Build
import android.os.LocaleList
import android.os.Vibrator
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.WindowManager
import android.webkit.CookieManager
import android.webkit.CookieSyncManager
import android.webkit.MimeTypeMap
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.content.PermissionChecker
import com.lib.framework.BuildConfig
import com.lib.framework.R
import com.lib.framework.entity.InstalledApkInfo
import com.lib.framework.manager.LogManager
import com.lib.framework.widget.WidgetUtil
import dalvik.system.DexFile
import java.io.File
import java.io.IOException
import java.net.NetworkInterface
import java.net.SocketException
import java.net.URLEncoder
import java.util.*

/**
 * Copyright (C), 2019-2019
 * FileName: AppUtil
 * Author: Kevin
 * Date: 2019-12-31 11:30
 * Description: 应用工具类
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class AppUtil {

    companion object {

        private val TAG = AppUtil::class.qualifiedName

        /**
         * 剪贴板标签
         */
        const val CLIP_LABEL = "Accompany"

        /**
         * 返回版本类型
         */
        fun getVersionType(): String {
            return BuildConfig.VERSION_TYPE
        }

        /**
         * 是否是 发布版本
         */
        fun isReleaseOfVersionType(): Boolean {
            return "Release" == getVersionType()
        }

        /**
         * 检查权限，并申请权限
         */
        private fun checkPermission(activity: Activity, permission: String, requestCode: Int) {
            if (checkPermissions(activity, permission)) {
                //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
                if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
                    WidgetUtil.showPromptToastError(activity, "请开通相关权限，否则无法正常使用本应用！")
                }

                //申请权限
                ActivityCompat.requestPermissions(activity, arrayOf(permission), requestCode)
            } else {
                //WidgetUtil.showPromptToastOK(activity, "授权成功！")
                LogManager.e(activity.componentName.className, "checkPermission: 已经授权！")
            }
        }

        /**
         * 检查权限
         */
        fun checkPermissions(context: Context, permission: String): Boolean {
            return if (Build.VERSION.SDK_INT < 23) {//一般android6以下会在安装时自动获取权限, 但在小米机上，可能通过用户权限管理更改权限
                true
            } else {
                if (context.applicationInfo.targetSdkVersion < 23) {
                    //targetSdkVersion<23时 即便运行在android6及以上设备 ContextWrapper.checkSelfPermission和Context.checkSelfPermission失效
                    //返回值始终为PERMISSION_GRANTED
                    //此时必须使用PermissionChecker.checkSelfPermission
                    PermissionChecker.checkPermission(context, permission, Binder.getCallingPid(),
                        Binder.getCallingUid(),
                        context.packageName) == PermissionChecker.PERMISSION_GRANTED
                } else {
                    context.checkSelfPermission(permission) === PackageManager.PERMISSION_GRANTED
                }
            }
        }


        /**
         * 根据Apk的路径获取包名
         *
         * @param context
         * @param apkPath
         * @return
         */
        fun getApkPackageName(context: Context, apkPath: String): String? {
            val pm = context.packageManager
            val info = pm.getPackageArchiveInfo(apkPath,
                PackageManager.GET_ACTIVITIES) ?: return null

            val appInfo = info.applicationInfo
            val appName = pm.getApplicationLabel(appInfo).toString()
            val packageName = appInfo.packageName // 得到安装包名称
            val version = info.versionName // 得到版本信息
            // Drawable icon = pm.getApplicationIcon(appInfo);//得到图标信息
            LogManager.i(TAG,
                "getApkPackageName(): appName = " + appName + ", packageName = " + packageName + ", version = " + version)

            return packageName
        }

        /**
         * 获取本应用的包名
         *
         * @param context
         * @return
         */
        fun getPackageName(context: Context): String {
            return context.packageName
        }

        /**
         * 得到当前版本号
         *
         * @param context
         * @return 当前版本号
         */
        fun getVersionCode(context: Context): Int {
            val packageManager = context.packageManager

            try {
                // 根据包名获取版本信息，0表示获取版本信息。
                val packageInfo = packageManager.getPackageInfo(context.packageName, 0)

                return packageInfo.versionCode
            } catch (e: PackageManager.NameNotFoundException) {
                LogManager.e(TAG, e)
            }

            return 0
        }

        /**
         * 获取版本号名称
         *
         * @param context 上下文
         * @return
         */
        fun getVersionName(context: Context): String {
            var verName = ""
            try {
                verName = context.packageManager.getPackageInfo(context.packageName, 0).versionName
            } catch (e: Exception) {
                LogManager.e(TAG, e)
            }
            return verName
        }

        /**
         * 安装apk
         *
         * @param context
         * @param apkPath
         */
        fun installApk(context: Context, apkPath: String) {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.setDataAndType(Uri.fromFile(File(apkPath)),
                "application/vnd.android.package-archive")

            /**
             * Context中有一个startActivity方法，Activity继承自Context，重载了startActivity方法。如果使用
             * Activity的startActivity方法
             * ，不会有任何限制，而如果使用Context的startActivity方法的话，就需要开启一个新的task
             * ，遇到上面那个异常的，都是因为使用了Context的startActivity方法。解决办法是，加一个flag。
             * intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             */
            if (!Activity::class.java.isAssignableFrom(context.javaClass)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }

            context.startActivity(intent)

        }

        /**
         * 根据包名，设置应用的启动页面的Intent，然后获取这个Intent的信息。
         *
         * @param context
         * @param packageName
         * @return
         */
        fun findActivitiesForPackage(context: Context, packageName: String): List<ResolveInfo> {
            val pm = context.packageManager
            val mainIntent = Intent(Intent.ACTION_MAIN, null)
            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER)
            mainIntent.`package` = packageName
            val apps = pm.queryIntentActivities(mainIntent, 0)
            return apps ?: ArrayList()
        }

        /**
         * 根据包名启动应用
         *
         * @param context
         * @param packageName
         */
        fun startApk(context: Context, packageName: String) {
            val matches = findActivitiesForPackage(context, packageName)
            if (matches != null && matches.size > 0) {
                val resolveInfo = matches.get(0)
                val activityInfo = resolveInfo.activityInfo
                startApk(context, activityInfo.packageName, activityInfo.name)
            }
        }

        /**
         * 根据包名、activity名启动应用
         *
         * @param context
         * @param packageName
         * @param className
         */
        fun startApk(context: Context, packageName: String, className: String) {
            val intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)

            val cn = ComponentName(packageName, className)
            intent.component = cn

            if (!Activity::class.java.isAssignableFrom(context.javaClass)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }

            context.startActivity(intent)
        }

        /**
         * 判读apk是否已经安装过了
         *
         * @param context
         * @param apkPackageName
         * @return
         */
        fun isInstalledApk(context: Context, apkPackageName: String): Boolean {

            val packageManager = context.packageManager
            val appList = packageManager.getInstalledPackages(0)

            for (i in appList.indices) {
                val pinfo = appList[i]

                if (pinfo.applicationInfo.packageName == apkPackageName) {
                    return true
                }

            }

            return false
        }

        /**
         * 获取已安装的apk列表
         *
         * @param context
         * @return
         */
        fun getInstalledApkMap(context: Context): HashMap<String, InstalledApkInfo> {

            val installedApkMap = HashMap<String, InstalledApkInfo>()

            val packageManager = context.packageManager
            val appList = packageManager.getInstalledPackages(0)

            for (i in appList.indices) {
                val pinfo = appList[i]
                if (pinfo != null) {
                    val appInfo = pinfo.applicationInfo

                    val installedApkInfo = InstalledApkInfo()
                    installedApkInfo.appName = packageManager.getApplicationLabel(appInfo)
                        .toString()
                    installedApkInfo.packageName = appInfo.packageName
                    installedApkInfo.versionName = pinfo.versionName
                    installedApkInfo.versionCode = pinfo.versionCode

                    // LogUtil.log(TAG, installedApkInfo.toString());

                    installedApkMap[appInfo.packageName] = installedApkInfo
                }

            }

            return installedApkMap
        }

        /**
         * 遍历本apk下指定的包，返回遍历到的类名列表
         *
         * @param context
         * @param packageName
         * @return 类名列表
         */
        fun traversePackage(context: Context, packageName: String): List<String> {
            val classNameList = ArrayList<String>()

            try {
                val path = context.packageManager.getApplicationInfo(context.packageName, 0)
                    .sourceDir
                val dexfile = DexFile(path)

                val entries = dexfile.entries()
                while (entries.hasMoreElements()) {
                    val name = entries.nextElement() as String
                    if (name.indexOf(packageName) >= 0) {
                        classNameList.add(name)
                    }
                }

            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }

            return classNameList
        }

        /**
         * 获取mac地址
         *
         * @param context
         * @return
         */
        fun getMacAddress(context: Context): String {
            val wifi = context.getSystemService(Context.WIFI_SERVICE) as WifiManager

            val info = wifi.connectionInfo

            return info.macAddress
        }

        /**
         * 获取IMEI号
         *
         * @param context
         * @return
         */
        fun getIMEI(context: Context): String {
            val telephonyManager = context.getSystemService(
                Context.TELEPHONY_SERVICE) as TelephonyManager
            return telephonyManager.deviceId
        }

        /**
         * 获取AndroidID
         *
         * @param context
         * @return
         */
        fun getAndroidID(context: Context): String? {
            return Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
        }

        /**
         * 判断指定的类名是否是当前顶部Activity。
         *
         * @return 是，返回ture；否，返回false。
         */
        fun isTopActivity(context: Context, classCanonicalName: String): Boolean {

            val activityManager = context.getSystemService(
                Context.ACTIVITY_SERVICE) as ActivityManager
            val cn = activityManager.getRunningTasks(1)[0].topActivity
            val className = cn?.className

            return className == classCanonicalName
        }

        /**
         * 用来判断服务是否后台运行
         *
         * @param context
         * @param className
         * 判断的服务名字
         * @return true 在运行 false 不在运行
         */
        fun isServiceRunning(context: Context, className: String): Boolean {
            var IsRunning = false

            val activityManager = context.getSystemService(
                Context.ACTIVITY_SERVICE) as ActivityManager

            val serviceList = activityManager.getRunningServices(Integer.MAX_VALUE)

            if (serviceList.size <= 0) {
                return false
            }

            for (i in serviceList.indices) {
                if (serviceList[i].service.className == className == true) {
                    IsRunning = true
                    break
                }
            }
            return IsRunning
        }

        /**
         * 判断某个界面是否在前台
         *
         * @param context
         * @param className
         * 某个界面名称
         */
        fun isForeground(context: Context?, className: String): Boolean {
            if (context == null || TextUtils.isEmpty(className)) {
                return false
            }

            val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val list = am.getRunningTasks(1)
            if (list != null && list.size > 0) {
                val cpn = list[0].topActivity
                if (className == cpn?.className) {
                    return true
                }
            }

            return false
        }

        /**
         * 判断网络是否可用
         *
         * @param context
         * @return
         */
        fun isNetworkConnected(context: Context?): Boolean {
            if (context != null) {
                val mConnectivityManager = context.getSystemService(
                    Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                val mNetworkInfo = mConnectivityManager.activeNetworkInfo
                if (mNetworkInfo != null) {
                    return mNetworkInfo.isAvailable
                }
            }
            return false
        }

        /**
         * 判断wifi是否可用
         *
         * @param context
         * @return
         */
        fun isWifiConnected(context: Context?): Boolean {
            if (context != null) {
                val mConnectivityManager = context.getSystemService(
                    Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                val mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(
                    ConnectivityManager.TYPE_WIFI)
                if (mWiFiNetworkInfo != null) {
                    return mWiFiNetworkInfo.isAvailable
                }
            }
            return false
        }

        /**
         * 判断Mobile网络是否可用
         *
         * @param context
         * @return
         */
        fun isMobileConnected(context: Context?): Boolean {
            if (context != null) {
                val mConnectivityManager = context.getSystemService(
                    Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                val mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(
                    ConnectivityManager.TYPE_MOBILE)
                if (mMobileNetworkInfo != null) {
                    return mMobileNetworkInfo.isAvailable
                }
            }
            return false
        }

        /**
         * 获取当前连接的网络类型
         *
         * @param context
         * @return
         */
        fun getConnectedNetType(context: Context?): Int {
            if (context != null) {
                val mConnectivityManager = context.getSystemService(
                    Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                val mNetworkInfo = mConnectivityManager.activeNetworkInfo
                if (mNetworkInfo != null && mNetworkInfo.isAvailable) {
                    return mNetworkInfo.type
                }
            }
            return -1
        }

        /**
         * 获取手机型号
         *
         * @return
         */
        fun getPhoneModel(): String {
            val osStr = removeSpace(Build.MODEL)
            return if (osStr.length < osStr.toByteArray().size) {
                try {
                    URLEncoder.encode(removeSpace(Build.MODEL), "UTF-8")
                } catch (e: Exception) {
                    e.printStackTrace()
                    "madeInChina"
                }

            } else {
                osStr
            }
        }

        /**
         * 获取系统版本
         *
         * @return
         */
        fun getSystemVersion(): String {
            return getZhString(Build.VERSION.RELEASE)
        }

        /**
         * 获取手机厂商
         *
         * @return  手机厂商
         */
        fun getDeviceBrand(): String {
            return getZhString(Build.BRAND)
        }

        /**
         * 系统语言
         */
        fun getPhoneLanguage(): String {
            val locale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                LocaleList.getDefault().get(0)
            } else {
                Locale.getDefault()
            }
            return getZhString(locale.language + "-" + locale.country)
        }

        /**
         * 处理中文字符串
         */
        private fun getZhString(str: String?): String {
            if (str == null) {
                return ""
            }
            val osStr = removeSpace(str)
            return if (osStr.length < osStr.toByteArray().size) {
                try {
                    URLEncoder.encode(removeSpace(str), "UTF-8")
                } catch (e: Exception) {
                    e.printStackTrace()
                    "madeInChina"
                }

            } else {
                osStr
            }
        }

        /**
         * 去掉空格
         */
        private fun removeSpace(model: String): String {
            return model.replace(" ".toRegex(), "")
        }

        /**
         * 获取渠道名称
         *
         * @param context
         * @return
         */
        fun getChannelName(context: Context): String? {
            try {
                val appInfo = context.packageManager.getApplicationInfo(context.packageName,
                    PackageManager.GET_META_DATA)

                // String channelNumber =
                // String.valueOf(appInfo.metaData.getInt("UMENG_CHANNEL")); //
                // 如果渠道名称是纯数字，那么必须使用appInfo.metaData.getInt()，否则会出异常。
                return appInfo.metaData.getString("UMENG_CHANNEL")
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }

            return null
        }

        /**
         * 获取手机号码
         *
         * @param context
         * @return
         */
        fun getPhoneNumber(context: Context): String {
            val telephonyManager = context.getSystemService(
                Context.TELEPHONY_SERVICE) as TelephonyManager
            return telephonyManager.line1Number
        }

        /**
         * 清除cookie
         *
         * @param context
         */
        fun clearCookie(context: Context?) {
            if (context == null) {
                return
            }

            CookieSyncManager.createInstance(context.applicationContext)
            CookieSyncManager.getInstance().startSync()
            CookieManager.getInstance().removeAllCookie()
        }

        /**
         * 获取屏幕宽度
         *
         * @param context
         * @return
         */
        fun getScreenWidth(context: Context): Int {
            val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val point = Point()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                wm.defaultDisplay.getRealSize(point)
            } else {
                wm.defaultDisplay.getSize(point)
            }
            return point.x
        }

        /**
         * 获取屏幕高度
         *
         * @param context
         * @return
         */
        fun getScreenHeight(context: Context): Int {
            val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val point = Point()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                wm.defaultDisplay.getRealSize(point)
            } else {
                wm.defaultDisplay.getSize(point)
            }
            return point.y
        }

        /**
         * 获取包含虚拟按键的屏幕高度
         */
        fun getScreenHeightWithVirtualKey(context: Context?): Int {
            if (context == null) {
                return 0
            }
            val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val display = windowManager.defaultDisplay
            val outPoint = Point()
            if (Build.VERSION.SDK_INT >= 19) {
                // 可能有虚拟按键的情况
                display.getRealSize(outPoint)
            } else {
                // 不可能有虚拟按键
                display.getSize(outPoint)
            }
            return outPoint.y
        }

        /**
         * 获取状态栏的高度
         *
         * @param activity
         * @return
         */
        fun getStatusBarHeight(activity: Activity): Int {
            val frame = Rect()
            activity.window.decorView.getWindowVisibleDisplayFrame(frame)
            return frame.top
        }

        /**
         * 判读是否存在状态栏
         *
         * @param activity
         * @return
         */
        fun isHasStatusBar(activity: Activity): Boolean {
            val attrs = activity.window.attributes

            return attrs.flags and WindowManager.LayoutParams.FLAG_FULLSCREEN != WindowManager.LayoutParams.FLAG_FULLSCREEN
        }

        /**
         * 获取IP
         *
         * @param context
         * @return
         */
        fun getIp(context: Context?): String {
            if (context == null) {
                return "0.0.0.0"
            }

            var ip: String? = null
            val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            if (wifiManager.isWifiEnabled) {
                // 获取wifi IP
                val wifiInfo = wifiManager.connectionInfo
                val ipAddress = wifiInfo.ipAddress
                ip = ((ipAddress and 0xFF).toString() + "." + (ipAddress shr 8 and 0xFF) + "." + (ipAddress shr 16 and 0xFF) + "." + (ipAddress shr 24 and 0xFF))
            } else {
                // 获取3g IP
                try {
                    val en = NetworkInterface.getNetworkInterfaces()
                    while (en.hasMoreElements()) {
                        val intf = en.nextElement()
                        val enumIpAddr = intf.inetAddresses
                        while (enumIpAddr.hasMoreElements()) {
                            val inetAddress = enumIpAddr.nextElement()
                            if (!inetAddress.isLoopbackAddress) {
                                ip = inetAddress.hostAddress.toString()
                            }
                        }
                    }
                } catch (ex: SocketException) {
                    LogManager.e(TAG, ex)
                }

            }

            if (ip == null || ip.isEmpty()) {
                ip = "0.0.0.0"
            }

            return ip
        }

        /**
         * 发短信
         */
        fun sendSMS(context: Context, phoneNumber: String, message: String) {
            //if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) {
            var intent = Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:$phoneNumber"))
            intent.putExtra("sms_body", message)

            if (!Activity::class.java.isAssignableFrom(context.javaClass)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }

            context.startActivity(intent)
            // }
        }

        /**
         * 复制文本到剪贴板
         */
        fun putTextIntoClip(context: Context, text: String) {
            val clipboardManager = context.getSystemService(
                Context.CLIPBOARD_SERVICE) as ClipboardManager
            // 创建ClipData对象
            val clipData = ClipData.newPlainText(CLIP_LABEL, text)
            // 添加ClipData对象到剪切板中
            clipboardManager.setPrimaryClip(clipData)
        }

        /**
         * 获取剪贴板的文本
         */
        fun getClipText(context: Context): String? {
            val clipboardManager = context.getSystemService(
                Context.CLIPBOARD_SERVICE) as ClipboardManager
            try {
                val data = clipboardManager.primaryClip
                val item = data?.getItemAt(0)
                return item?.text.toString()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            return null
        }

        /**
         * 获取剪贴板文本的标签
         */
        fun getClipTextLabel(context: Context): String? {
            val clipboardManager = context.getSystemService(
                Context.CLIPBOARD_SERVICE) as ClipboardManager
            try {
                val data = clipboardManager.primaryClip
                return data?.description?.label?.toString()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            return null
        }

        /**
         * 打开浏览器
         */
        fun openBrowser(context: Context, url: String) {
            val urlTmp = if (!(url.startsWith("http://") || url.startsWith("https://"))) {
                "http://$url"
            } else {
                url
            }

            val intent = Intent()
            intent.data = Uri.parse(urlTmp)
            intent.action = Intent.ACTION_VIEW
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }

        /**
         * 其他应用打开文件
         */
        fun openFile(context: Context, file: File) {
            val uri = Uri.parse("file://${file.absolutePath}")
            val intent = Intent()
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.action = Intent.ACTION_VIEW
            val type = getMIMEType(file)
            intent.setDataAndType(uri, type)
            if (type != "*/*") {
                try {
                    context.startActivity(intent)
                } catch (e: Exception) {
                    WidgetUtil.showPromptToastError(context,
                        context.getString(R.string.file_cant_open))
                }
            } else {
                try {
                    context.startActivity(Intent.createChooser(intent,
                        context.getString(R.string.select_app_to_open)))
                } catch (e: Exception) {
                    WidgetUtil.showPromptToastError(context,
                        context.getString(R.string.file_cant_open))
                }
            }
        }

        /**
         * 获取文件的 MIME Type
         */
        fun getMIMEType(file: File): String? {
            val type = "*/*"
            val fName = file.name
            // 获取后缀名前的分隔符"."在fName中的位置。
            val dotIndex = fName.lastIndexOf("")
            if (dotIndex < 0) {
                return type
            }
            /* 获取文件的后缀名 */
            val end = fName.substring(dotIndex + 1, fName.length).toLowerCase()
            if (end === "") return type
            val mimeTypeMap = MimeTypeMap.getSingleton()
            return if (mimeTypeMap.hasExtension(end)) {
                mimeTypeMap.getMimeTypeFromExtension(end)
            } else type
        }

        /**
         * 获取国家码
         */
        fun getCountryCode(context: Context): String {
            val manager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            return manager.simCountryIso.toUpperCase()
        }

        /**
         * 是否是飞行模式
         */
        fun isAirModeOn(context: Context): Boolean {
            return Settings.System.getInt(context.contentResolver,
                android.provider.Settings.Global.AIRPLANE_MODE_ON, 0) == 1
        }

        /**
         * 播放系统提示音
         */
        fun palyRingtone(context: Context) {
            val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) ?: return
            val rt = RingtoneManager.getRingtone(context.applicationContext, uri) ?: return
            rt.play()
        }

        /**
         * 震动
         */
        fun vibrate(context: Context, milliseconds: Long) {
            val vibrator = context.getSystemService(Service.VIBRATOR_SERVICE) as? Vibrator ?: return
            vibrator.vibrate(milliseconds)
        }

        /**
         * 循环震动， 要结束震动调用 virateCancle()
         *
         * @param pattern 震动时间数组，一次循环按照 数组的震动时间 一一震动
         * @param repeatStart 震动时间数组中的索引，从哪个时间开始，0 从第一个开始
         */
        fun vibrate(context: Context, pattern: LongArray, repeatStart: Int) {
            val vibrator = context.getSystemService(Service.VIBRATOR_SERVICE) as? Vibrator ?: return
            vibrator.vibrate(pattern, repeatStart)
        }

        /**
         * 取消震动
         */
        fun virateCancle(context: Context) {
            val vibrator = context.getSystemService(Service.VIBRATOR_SERVICE) as? Vibrator ?: return
            vibrator.cancel()
        }

        /**
         * 把图片加入相册
         */
        fun addPicToGallery(context: Context, filePath: String) {
            addPicToGallery(context, File(filePath))
        }

        /**
         * 把图片加入相册
         */
        fun addPicToGallery(context: Context, file: File) {
            if (!file.exists()) return

            addPicToGallery(context, Uri.fromFile(file))
        }

        /**
         * 把图片加入相册
         */
        fun addPicToGallery(context: Context, uri: Uri) {
            val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            mediaScanIntent.data = uri
            context.sendBroadcast(mediaScanIntent)
        }

        /**
         * 发送通知
         */
        fun sendNotification(context: Context, title: String, content: String, iconResid: Int,
                             pendingIntent: PendingIntent, notifyId: Int) {
            val manager = context.getSystemService(
                Context.NOTIFICATION_SERVICE) as NotificationManager

            val id = "chongwa01"
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val name = "chongwa01"
                val channel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT)
                manager.createNotificationChannel(channel)
            }

            //创建通知
            val notificationBuilder = NotificationCompat.Builder(context, id).setTicker(content)
                .setContentTitle(title).setContentText(content).setWhen(System.currentTimeMillis())
                .setSmallIcon(iconResid)
                .setLargeIcon(BitmapFactory.decodeResource(context.resources, iconResid))
                .setContentIntent(pendingIntent).setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setDefaults(NotificationCompat.DEFAULT_ALL)

//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                notificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC)
//                notificationBuilder.setFullScreenIntent(pendingIntent, false)
//            }

            val notification = notificationBuilder.build()
            manager.notify(notifyId, notification)
        }

        /**
         * 发送邮件
         */
        fun sendEmail(context: Context, toEmailAddress: String) {
            val intent = Intent(Intent.ACTION_SENDTO)
            intent.data = Uri.parse("mailto:$toEmailAddress")
//            intent.putExtra(Intent.EXTRA_SUBJECT, "这是标题")
//            intent.putExtra(Intent.EXTRA_TEXT, "这是内容")

            if (!Activity::class.java.isAssignableFrom(context.javaClass)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }

            try {
                context.startActivity(intent)
            } catch (e: Exception) {
                WidgetUtil.showPromptToastError(context, context.getString(R.string.sendEmailFail))
            }
        }

        /**
         * 获取系统设置的语言
         */
        fun getSystemLanguage(): String {
            val locale = Locale.getDefault()
            return locale.language + "-" + locale.country
        }
    }
}